class ReservationsController < ApplicationController

  def index
    @client = Client.find(params[:client_id])
    @reservations = @client.reservations
  end

  def show
    @client = Client.find(params[:client_id])
    @reservation = @client.reservations.find(params[:id])
  end

  def new
    @client = Client.find(params[:client_id])
    @reservation = @client.reservations.build
    @chambres = Chambre.find(:all, :conditions => ["status LIKE ?", "Libre"]).paginate(:page => params[:page], :per_page => 10)
    
  end

  def create
    @client = Client.find(params[:client_id])
    @reservation = @client.reservations.build(params[:reservation])
    
    if @reservation.save
      after_create
      redirect_to client_reservation_url(@client, @reservation)
    else
      render :action => "new"
    end
  end
  
  def after_create
    @reservations = Reservation.find(:all)
    @derniere_resa = @reservations[-1]
    @chambre = Chambre.find(@derniere_resa.chambre_id)
    if @derniere_resa.date_arrivee and @derniere_resa.date_depart
      @change = @chambre.update_attribute(:status, "Occupée")
    else
      @change = @chambre.update_attribute(:status, "Libre")
    end
  end

  def edit
    @client = Client.find(params[:client_id])
    @reservation = @client.reservations.find(params[:id])
  end

  def update
    @client = Client.find(params[:client_id])
    @reservation = Reservation.find(params[:id])
    if @reservation.update_attributes(params[:reservation])
      redirect_to client_reservation_url(@client, @reservation)
    else
      render :action => "edit"
    end
  end

  def destroy
    @client = Client.find(params[:client_id])
    @reservation = Reservation.find(params[:id])
    @reservation.destroy

    respond_to do |format|
      format.html { redirect_to client_reservations_path(@client) }
      format.xml  { head :ok }
    end
  end

end